﻿namespace Suture.Strategies
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    public class GreediestConstructorStrategy<T> : IConstructorStrategy
    {
        public ConstructorInfo GetConstructor(Dictionary<string, object> constructorArgs)
        {
            var constructors =
                typeof(T).GetConstructors()
                         .Select(ctor => new { ConstructorInfo = ctor, Parameters = ctor.GetParameters() });

            if (constructorArgs.Any())
            {
                constructors =
                    constructors.Where(
                        ctor =>
                        ctor.Parameters.Any(
                            p => constructorArgs.Keys.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase)));
            }

            return constructors.OrderByDescending(ctor => ctor.Parameters.Count()).Select(c => c.ConstructorInfo).First();
        }
    }
}